import { Component, ViewChild } from '@angular/core';
import { Router } from '@angular/router';
import { CascaderItem, DValidateRules, FileUploader, FormLayout, IFileOptions, IUploadOptions } from 'ng-devui';
import { DeviceToolsService } from 'src/app/@core/services/device-tools/device-tools.service';
import { DeviceService } from 'src/app/@core/services/device.ts/device.service';
import { EncodeRulesService } from 'src/app/@core/services/encoderRule/encode-rules.service';
import { environment } from 'src/environments/environment';
@Component({
  selector: 'app-add-device-tool',
  templateUrl: './add-device-tool.component.html',
  styleUrls: ['./add-device-tool.component.scss']
})
export class AddDeviceToolComponent {
  msg:any;
  layoutDirection: FormLayout = FormLayout.Horizontal;
  options: any=[];
  status:any=['报废','在用'];
  chosenItem = '在用';
  z
  option: Array<number> = [];//设备分类
  productionDate: Date
  assemblyTime: Date
  device = {
    equipmentName: "",
    equipmentNum: "",
    equipmentCategoryId: null,
    model: "",
    site: "",
    purchaseDate: "",
    productionDate: "",
    assetsCode: "",
    assemblyTime: "",
    isEnabled: true,
    level: "",
    isScheduling: true,
    workshop: "",
    maintenanceTypeId: 0,
    note: "",
    priority: null
  }
  fixture = {
    fixtureNum: "",
    fixtureName: "",
    fixtureTypeId: null,
    note: "",
    fileURL: "",
    addFileURL: "",
    model: "",
    purchaseDate: null,
    isEnabled: false,
  }
  msgs: Array<Object> = [];
  message: Array<Object> = [];
  FixtureRules:{[key:string]:DValidateRules} = {
    fixtureNum: {
      messageShowType:'text',
      validators: [
        { required: true ,message: '*工装夹具编码不能为空' },
        { minlength: 2, message: '*工装夹具编码长度至少为2' },
        { maxlength: 40, message: '*工装夹具编码长度至多为40' },
        { pattern: /^[^\s]*$/, message: '*工装夹具编码不能包含空格' }
      ],
    },
    fixtureName: {
      messageShowType:'text',
      validators: [
        { required: true ,message: '*工装夹具名称不能为空' },
        { maxlength: 40, message: '*工装夹具名称长度至多为40' },
        { pattern: /^[^\s]*$/, message: '*工装夹具名称不能包含空格' }
      ],
    },
    model: {
      messageShowType:'text',
      validators: [
      ],
    },
    fixtureTypeId: {
      messageShowType:'text',
      validators: [
        { required: true ,message: '*工装夹具分类不能为空' },
      ],
    },
  }
  file: any;
  fileUploaders: Array<FileUploader> = [];
  CANCELUPLOAD: string;
  isDropOver = false;
  fileOptions: IFileOptions = {
    multiple: true,
    accept: '.png,.jpg,.jpeg,.gif,.bmp,.wbmp,.webp',
  };
  uploadedFiles2: any[] = [];
  uploadedFiles: Array<Object> = [];
  uploadOptions: IUploadOptions = {
    uri:environment.apiUrl+'/Fixture/UploadAvatar',
    maximumSize: 1024,
    method: 'post',
    checkSameName: true,
    fileFieldName:"file",
  };
  fixtureImgUrls: any;
  constructor(private EncodeRulesService:EncodeRulesService,private Router:Router,private DeviceToolsService:DeviceToolsService){
  }
  ngOnInit(): void {
   this.EncodeRulesService.GenerateWarehouseCodeRule('工装夹具编码','工装夹具编码').subscribe((res: any) => {
      this.fixture.fixtureNum = res
   });
   this.DeviceToolsService.GetPagedFixtureTypesWithChildren(1,999).subscribe((res: any) => {
    this.options = this.convertToCascaderItem(res.items);
    });
   this.fixture.isEnabled=this.statusToBoolean(this.chosenItem);
  }
  convertToCascaderItem(data: any[]): CascaderItem[] {
    return data.map(item => {
      let cascaderItem: CascaderItem = {
        label: item.fixtureTypeName,
        value: item.fixtureTypeId,
      };
      if (item.subFixtureTypes) {
        cascaderItem.children = this.convertToCascaderItem(item.subFixtureTypes);
      }
      return cascaderItem;
    });
  }//转换数据格式为华为库练级菜单的数据格式
  CascaderonChanges($event:any){
    this.fixture.fixtureTypeId = $event[$event.length-1]
  }
  submit(){
    if(this.fixture.fixtureNum&&this.fixture.fixtureName&&this.fixture.fixtureTypeId){
      this.DeviceToolsService.CreateFixture(this.fixture).subscribe((res: any) => {
        this.showToast('success','提示','添加成功');
        setTimeout(() => {
          this.Router.navigate(['/pages/device-tools/device-tool'])
        }, 1500);
      },(error) => {
        if(error.status==404){
          this.showToast('error', '失败', '服务器连接失败');
        }else{
          this.showToast('error', '失败', error.error);
        }
      }
      )
    }
  }
  cancle(){
    this.Router.navigate(['/pages/device-tools/device-tool'])
  }
  showToast(type: any,summary:any,content:any) {
    switch (type) {
    default:
      this.msgs = [{ severity: type, summary: summary, content: content }];
    }
  }//提示框
  statusChange(){
    this.fixture.isEnabled=this.statusToBoolean(this.chosenItem);
  }
  statusToBoolean(status: string): boolean {
    if (status === '在用') {
      return true;
    } else if (status === '报废') {
      return false;
    } else {
      throw new Error('Invalid status: ' + status);
    }
  }
  deleteFile(currFile: FileUploader) {
    this.fileUploaders = this.fileUploaders.filter((fileUploader) => {
      return currFile !== fileUploader;
    });
    const responseObj =this.fileUploaders.map(item=>JSON.parse(item.response).avatarUrl);
    const trimmedUrls = responseObj.map((url: string) => url.replace(environment.modifiedApiUrl, ""));
    const resultString = trimmedUrls.join(',');
    this.fixture.fileURL = resultString;
  }
  getImagesArray(fileURL: string): string[] {
    if (!fileURL) {
      return [];
    }
    let urls = fileURL.split(',');
    urls = urls.map(url => environment.modifiedApiUrl + url);
    return urls;
  }
  onSuccess(event: any) {
    const repsonse =event.map((item: { response: string; }) => JSON.parse(item.response).avatarUrl);
    const trimmedUrls = repsonse.map((url: string) => url.replace(environment.modifiedApiUrl, ""));
    const resultString = trimmedUrls.join(',');
    if(this.fixture.fileURL){
      this.fixture.fileURL += ',' + resultString;
    }else{
      this.fixture.fileURL = resultString;
    }
  }
  importFormExcel(event: any) {
    this.file = event.target.files[0];
    this.DeviceToolsService.UploadAttachment(this.file).subscribe((res: any) => {
      this.file.attachmentUrl = res.attachmentUrl;
      this.uploadedFiles2.push(this.file);
      res.attachmentUrl = res.attachmentUrl.replace(environment.modifiedApiUrl, "");
      if(this.fixture.addFileURL){
        this.fixture.addFileURL += ',' + res.attachmentUrl;
      }
      else{
        this.fixture.addFileURL = res.attachmentUrl;
      }
    })
  }
  @ViewChild('fileInput1') fileInput1: any;
  onButtonClick() {
    // 当按钮被点击时，触发文件输入的点击事件
    this.fileInput1.nativeElement.click();
  }
  deleteFile2(index:any){
    const urls = this.fixture.addFileURL.split(",");
    urls.splice(index, 1);
    this.fixture.addFileURL = urls.join(",");
    this.uploadedFiles2.splice(index, 1);
  }
}
